//
//  XLRCIMDataBaseManager.m
//  XLBaseModule
//
//  Created by 于鹏 on 2017/9/12.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "XLRCIMDataBaseManager.h"
static NSString *const userTableName = @"USERTABLE";
@implementation XLRCIMDataBaseManager

+ (XLRCIMDataBaseManager *)shareInstance {
    static XLRCIMDataBaseManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[XLRCIMDataBaseManager alloc]init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self createUserTableIfNeed];
    }
    return self;
}

//创建用户存储表
- (void)createUserTableIfNeed {
    BOOL isExistTable = [self isExistWithTableName:userTableName];
    if (!isExistTable) {
        NSArray *keys = @[@"userID",@"nickName",@"portraitUrl"];
        BOOL result = [self createTableWithTableName:userTableName keys:keys];
        if (result) {
            
        } else {
            
        }
    } else {
        NSLog(@"%@表已经存在",userTableName);
    }
}

//从表中获取用户信息
- (RCUserInfo *)getUserByUserId:(NSString *)userId {
    __block RCUserInfo *model = nil;
    NSArray *whereArr = @[[NSString stringWithFormat:@"%@,%@,%@",@"userID", @"=", userId]];
    NSArray *queryArr = [self queryWithTableName:userTableName keys:@[@"userID"] where:whereArr];
    for (NSDictionary *dic in queryArr) {
        if ([userId isEqualToString:dic[@"userID"]]) {
            model = [[RCUserInfo alloc]init];
            model.userId = dic[@"userID"];
            model.name = dic[@"nickName"];
            model.portraitUri = dic[@"portraitUrl"];
        } else {
            
        }
    }
    return model;
}

//存储用户信息
- (void)insertUserToDB:(RCUserInfo *)user {
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    [dic setValue:user.userId forKey:@"userID"];
    [dic setValue:user.name forKey:@"nickName"];
    [dic setValue:user.portraitUri forKey:@"portraitUrl"];
    NSMutableArray* where = [NSMutableArray array];
    if (![user.userId isEqualToString:@""]) {
        [where addObject:@"userID"];
        [where addObject:@"="];
        [where addObject:user.userId];
    }
    
    NSArray *arr = [self queryWithTableName:userTableName];
    for (NSDictionary *dic in arr) {
        if ([user.userId isEqualToString:dic[@"userID"]]) {
            return;
        }
    }
    
    BOOL result = [self insertIntoTableName:userTableName Dict:dic];//插入语句
    if (result) {
        
    } else {
        
    }
}

@end
